<!--
 * @Description: 取消结算详情
 * @Autor: 何兴家
 * @Date: 2021-01-14 16:21:14
 * @LastEditors: 何兴家
 * @LastEditTime: 2021-03-30 14:19:38
-->
<template>
  <div v-loading="pageIsLoading">
    <!-- 顶部按钮区 -->
    <div class="topBtnsWrap">
      <ButtonArea :style="{ paddingLeft: '0px', paddingRight: '0px' }">
        <AjaxButton type="primary" :disabled="btnDisabledStatus" :click="handleCancelFeeSettlement">取消结算</AjaxButton>
        <auditResult v-if="defaultOrderType == 'repair' && appId != 'beijing'" :disabled="false" :roNo="roNo" />
        <el-button type="primary" @click="handleCancel">取消</el-button>
      </ButtonArea>
      <ButtonArea :style="{ paddingLeft: '0px', paddingRight: '0px' }">
        <el-button icon="el-icon-close" style="position: relative;right: -10px" @click="handleCancel">关闭</el-button>
      </ButtonArea>
    </div>

    <!-- 工单信息 -->
    <div class="box" v-if="orderType == 'repair'">
      <BreakSpace label="工单信息" :containerStyle="{ marginBottom: '10px' }"></BreakSpace>
      <FormPanel ref="orderInfoForm" :list="orderInfoFormList" :cols="4" :labelWidth="100" :isSubmitBtn="false"></FormPanel>
    </div>

    <!-- 车主车辆信息 -->
    <div class="box" v-if="orderType == 'repair'">
      <BreakSpace label="车主车辆信息" :containerStyle="{ marginBottom: '10px' }"></BreakSpace>
      <FormPanel ref="carOwnerForm" :list="carOwnerFormList" :cols="4" :labelWidth="100" :isSubmitBtn="false"></FormPanel>
    </div>

    <!-- 配件销售单信息 -->
    <div class="box" v-if="orderType == 'part'">
      <BreakSpace label="配件销售单信息" :containerStyle="{ marginBottom: '10px' }"></BreakSpace>
      <FormPanel ref="partSaleForm" :list="partSaleFormList" :cols="4" :labelWidth="100" :isSubmitBtn="false"></FormPanel>
    </div>

    <!-- 结算单信息 -->
    <div class="box">
      <BreakSpace label="结算单信息" :containerStyle="{ marginBottom: '10px' }"></BreakSpace>
      <FormPanel ref="balanceForm" :list="ballanceFormList" :cols="4" :labelWidth="100" :isSubmitBtn="false"></FormPanel>
    </div>

    <!-- 维修配件项目详情及金额计算框 -->
    <div class="detailWrap">
      <div class="left">
        <el-tabs v-model="activeDetailTab">
          <el-tab-pane label="维修项目" name="维修项目" v-if="orderType == 'repair'">
            <FilterTable
              ref="repairLabourTable"
              columnsRef="repair_repairReception_feesettlement_balanceDetail_labour"
              height="auto"
              :columns="repairLabourColumns"
              :dataSource="repairLabourTableDataSource"
              :onColumnsChange="columns => (this.repairLabourColumns = columns)"
            >
            </FilterTable>
          </el-tab-pane>
          <el-tab-pane label="维修材料" name="维修材料" v-if="orderType == 'repair'">
            <FilterTable
              ref="repairPartTable"
              columnsRef="repair_repairReception_feesettlement_balanceDetail_part"
              height="auto"
              :columns="repairPartColumns"
              :dataSource="repairPartTableDataSource"
              :onColumnsChange="columns => (this.repairPartColumns = columns)"
            >
            </FilterTable>
          </el-tab-pane>
          <el-tab-pane label="附加项目" name="附加项目" v-if="orderType == 'repair'">
            <FilterTable
              ref="additionItemTable"
              columnsRef="repair_repairReception_feesettlement_balanceDetail_additionItem"
              height="auto"
              :columns="additionItemColumns"
              :dataSource="additionItemTableDataSource"
              :onColumnsChange="columns => (this.additionItemColumns = columns)"
            >
            </FilterTable>
          </el-tab-pane>
          <el-tab-pane label="销售材料" name="销售材料" v-if="orderType == 'part'">
            <FilterTable
              ref="salesPartTable"
              columnsRef="repair_repairReception_feesettlement_balanceDetail_salesPart"
              height="auto"
              :columns="salesPartColumns"
              :dataSource="salesPartTableDataSource"
              :onColumnsChange="columns => (this.salesPartColumns = columns)"
            >
            </FilterTable>
          </el-tab-pane>
        </el-tabs>
        <!-- 折扣率 -->
        <!-- <FormPanel ref="discountForm" :list="discountFormList" :cols="4" :labelWidth="90" :isSubmitBtn="false"></FormPanel> -->
        <!-- 优惠券 -->
        <BreakSpace label="优惠金额" :containerStyle="{ marginBottom: '10px' }" v-show="false"></BreakSpace>
        <FilterTable
          v-show="false"
          ref="discountCouponTable"
          columnsRef="repair_repairReception_feesettlement_balanceDetail_discountCoupon"
          height="auto"
          :columns="discountCouponColumns"
          :dataSource="discountCouponTableDataSource"
          :onColumnsChange="columns => (this.discountCouponColumns = columns)"
        >
          <template slot="controls">
            <el-button type="primary" :disabled="btnDisabledStatus">新增优惠</el-button>
          </template>
        </FilterTable>
        <!-- 应收实收收费对象 -->
        <el-tabs v-model="activeReceiveTabs">
          <el-tab-pane name="应收" label="应收">
            <FilterTable
              ref="receivableTable"
              columnsRef="repair_repairReception_feesettlement_balanceDetail_receivable"
              height="auto"
              :isSelectColumn="false"
              :columns="receivableColumns"
              :dataSource="receivableTableDataSource"
              :onColumnsChange="columns => (this.receivableColumns = columns)"
            >
            </FilterTable>
          </el-tab-pane>
          <el-tab-pane name="实收" label="实收">
            <FilterTable
              ref="realIncomeTable"
              columnsRef="repair_repairReception_feesettlement_balanceDetail_realIncome"
              height="auto"
              :columns="realIncomeColumns"
              :dataSource="realIncomeTableDataSource"
              :onColumnsChange="columns => (this.realIncomeColumns = columns)"
            >
              <template slot="controls">
                <!-- <el-button type="primary">新增收费对象</el-button> -->
              </template>
            </FilterTable>
          </el-tab-pane>
        </el-tabs>
      </div>
      <div class="right">
        <BreakSpace label="费用信息" :containerStyle="{ marginBottom: '10px' }"></BreakSpace>
        <FormPanel ref="costInfoForm" :list="costInfoFormList" :cols="1" :labelWidth="90" :isSubmitBtn="false"></FormPanel>
      </div>
    </div>
  </div>
</template>

<script>
import _ from 'lodash';
import { dictionary } from '@/utils/dictMixin';
import { confirmAction, notifyAction, findFormItem, findTableItem, setRound, jsonToHump } from '@/utils';
import { createOrderInfoList, createCarOwnerFormList, createPartSaleFormList, createBallanceFormList, createCostInfoFormList, createDiscountFormList } from '../feesSettlement/formStatement.js';
import { getAppId } from '@/assets/js/auth';

import {
  createRepairLabourColumns,
  createRepairPartColumns,
  createAdditionItemColumns,
  createSalesPartColumns,
  createDiscountCouponColumns,
  createReceivableColumns,
  createRealIncomeColumns
} from '../feesSettlement/tableStatement.js';
import { queryUserControlDiscountMode1 } from '@/api/repair/repairReception/feesSettlement';
import { queryCancelSettlementRepairOrderDetail, queryCancelSettlementPartRepairOrderDetail, cancelBalanceAccounts } from '@/api/repair/repairReception/cancelFeeSettlement';
import { getWxlxSelect, getSfqfSelect } from '@/api/repair/repairReception/customer';
import { getSystemDefault, getDealerUser } from '@/api/repair/common';
import { getDiscountmodes } from '@/api/repair/repairBusiness/preferentialWay';

import auditResult from '../customer/auditResult';

export default {
  props: ['orderDetail', 'defaultPageType', 'defaultOrderType'],
  components: { auditResult },
  mixins: [dictionary],
  data() {
    this.orderInfo = {}; // 储存查询回来的工单信息

    return {
      activeDetailTab: '维修项目', // 激活的详情tab
      activeReceiveTabs: '应收', // 激活的应收实收搜tab

      // 表单声明
      orderInfoFormList: createOrderInfoList.call(this),
      carOwnerFormList: createCarOwnerFormList.call(this),
      partSaleFormList: createPartSaleFormList.call(this),
      ballanceFormList: createBallanceFormList.call(this),
      discountFormList: createDiscountFormList.call(this),
      costInfoFormList: createCostInfoFormList.call(this),

      // 表格声明
      repairLabourColumns: createRepairLabourColumns.call(this),
      repairPartColumns: createRepairPartColumns.call(this),
      additionItemColumns: createAdditionItemColumns.call(this),
      salesPartColumns: createSalesPartColumns.call(this),
      discountCouponColumns: createDiscountCouponColumns.call(this),
      receivableColumns: createReceivableColumns.call(this),
      realIncomeColumns: createRealIncomeColumns.call(this),

      // 页面数据
      orderType: 'repair', // 单据类型 repair --维修工单 part --配件销售单
      pageType: 'edit', // 页面类型 edit --编辑/结算 detail --详情展示
      pageIsLoading: false, // 页面加载状态
      appId: getAppId(),

      repairLabourTableDataSource: [], // 维修项目table数据源
      repairPartTableDataSource: [], // 维修配件table数据源
      additionItemTableDataSource: [], // 附加项目table数据源
      salesPartTableDataSource: [], // 配件销售table数据源
      discountCouponTableDataSource: [], // 优惠券table数据源
      receivableTableDataSource: [], // 应收table数据源
      realIncomeTableDataSource: [] // 实收table数据源
    };
  },
  computed: {
    // 按钮禁用状态
    btnDisabledStatus() {
      return this.pageType == 'detail';
    },
    // 工单号
    roNo() {
      return this.defaultOrderType == 'repair' ? findFormItem(this.orderInfoFormList, 'RO_NO').initialValue : '';
    }
  },
  mounted() {
    this.orderType = this.defaultOrderType;
    this.pageType = this.defaultPageType;
    if (this.defaultOrderType == 'repair') {
      this.queryOrderDataByRoNo(this.orderDetail.RO_NO);
      // this.queryDiscountModelByRoNo(this.orderDetail.RO_NO);
    } else {
      this.activeDetailTab = '销售材料';
      console.log(this.orderDetail, 'hexj001');
      this.querySalesPartOrderDataBySalesPartNo(this.orderDetail.SALES_PART_NO);
      // this.queryDiscountModelByRoNo();
    }
    this.initPageDicts();
    this.disabledPageAllField();
  },
  methods: {
    /**
     * 初始化查询，字典项等
     */
    initPageDicts() {
      this.queryRepairTypeDict();
      this.querySfqfDict();
      this.queryTaxRate();
      this.queryDealerUser();
    },
    // 获取维修类型
    async queryRepairTypeDict() {
      let res = await getWxlxSelect();
      if (res.resultCode == 200) {
        let repairTypeDict = res.data.map(item => ({ text: item.REPAIR_TYPE_NAME, value: item.REPAIR_TYPE_CODE + '' }));
        // this.repairTypeList = res.data;

        findFormItem(this.orderInfoFormList, 'REPAIR_TYPE_CODE').itemList = repairTypeDict;
        let tableTarget = findTableItem(this.repairLabourColumns, 'REPAIR_TYPE_CODE');
        tableTarget.dictItems = tableTarget.filterItems = repairTypeDict;
      }
    },
    // 获取收费区分
    async querySfqfDict() {
      let res = await getSfqfSelect();
      if (res.resultCode == 200) {
        let sfqfDict = res.data.map(item => ({ text: item.CHARGE_PARTITION_NAME, value: item.CHARGE_PARTITION_CODE }));
        // this.sfqfDict = sfqfDict;
        let tableTargets = [
          findTableItem(this.repairLabourColumns, 'CHARGE_PARTITION_CODE'),
          findTableItem(this.repairPartColumns, 'CHARGE_PARTITION_CODE'),
          findTableItem(this.additionItemColumns, 'CHARGE_PARTITION_CODE')
        ];
        tableTargets.forEach(item => {
          item.dictItems = item.filterItems = sfqfDict;
        });
      }
    },
    // 根据工单号获取优惠模式权限(废弃，取消结算仅为页面翻译用 使用下方接口)
    async queryDiscountModelByRoNo(roNo) {
      let res = await queryUserControlDiscountMode1(roNo);
      if (res.resultCode == 200 && res.data) {
        let disCountModeDict = res.data.discountModeList.map(item => ({ text: item.PREFERENTIAL_TOTAL, value: item.DISCOUNT_MODE_CODE }));
        findFormItem(this.costInfoFormList, 'discountModeCode').itemList = disCountModeDict;
      }
    },
    // 根据优惠模式代码查询优惠模式详情
    async queryDiscountModelByCode(code) {
      let res = await getDiscountmodes({
        discountModeCode: code,
        currentPage: 1,
        pageSize: 20,
        pageNum: 1,
        limit: 20,
        current: 1,
        size: 20
      });
      if (res.resultCode == 200 && res.data.rows.length) {
        findFormItem(this.costInfoFormList, 'discountModeCode').itemList = [
          {
            text: res.data.rows[0].discountModeName,
            value: res.data.rows[0].discountModeCode
          }
        ];
      }
    },
    // 查询税率
    async queryTaxRate() {
      let res = await getSystemDefault({ itemCode: 1003 });
      if (res.resultCode == 200) {
        this.tax = res.data;
        findFormItem(this.costInfoFormList, 'tax').initialValue = res.data;
      }
    },
    // 查询全部人员（翻译用）
    async queryDealerUser() {
      let res = await getDealerUser();
      if (res.resultCode == 200) {
        let userDicts = res.data.map(item => ({ text: item.employeeName, value: item.userId + '' }));
        findFormItem(this.orderInfoFormList, 'SERVICE_ADVISOR').itemList = userDicts;
        findTableItem(this.repairLabourColumns, 'TECHNICIAN').dictItems = userDicts;
      }
    },

    /**
     * 页面函数
     */
    // 禁用页面全部字段
    disabledPageAllField() {
      this.orderInfoFormList.forEach(item => {
        item.disabled = true;
      });
      this.ballanceFormList.forEach(item => {
        item.disabled = true;
      });
      this.discountFormList.forEach(item => {
        item.disabled = true;
      });
      this.costInfoFormList.forEach(item => {
        item.disabled = true;
      });
    },
    // 根据工单号查询工单详情
    async queryOrderDataByRoNo(roNo) {
      this.pageIsLoading = true;
      try {
        let res = await queryCancelSettlementRepairOrderDetail({ roNo });
        if (res.resultCode == 200) {
          // 处理部分字段有区别字段
          res.data.DISCOUNT_AMOUNT = res.data.TOTAL_DISCOUNT_AMOUNT;
          // res.data.CALC_RECEIVE_AMOUNT = res.data.RECEIVE_AMOUNT; 改为后端处理 2021/02/01
          res.data.REMARKDETAIL = res.data.REMARK;
          res.data.ARR_BALANCE = res.data.ARR_BALANCE == 10041001 ? '1' : '0';

          // 查询优惠模式(翻译用)
          res.data.DISCOUNT_MODE_CODE && this.queryDiscountModelByCode(res.data.DISCOUNT_MODE_CODE);

          let cloneData = _.cloneDeep(res.data);
          console.log(cloneData, 'hexj001');
          jsonToHump(cloneData); // 费用信息部分表单字段为小写，转换后赋值
          let formLists = [...this.orderInfoFormList, ...this.carOwnerFormList, ...this.ballanceFormList];
          formLists.forEach(item => {
            item.initialValue = res.data[item.fieldName] || '';
          });
          this.costInfoFormList.forEach(item => {
            item.initialValue = cloneData[item.fieldName] || '';
          });

          this.repairLabourTableDataSource = res.data.labourList;
          this.repairPartTableDataSource = res.data.partList;
          this.additionItemTableDataSource = res.data.addLabourlist;
          this.discountCouponTableDataSource = []; // 优惠券列表暂无
          this.receivableTableDataSource = res.data.receiveablelist;
          this.realIncomeTableDataSource = res.data.realList;
        }
      } catch (err) {
        console.log(err, '查询工单详情失败');
      } finally {
        this.pageIsLoading = false;
      }
    },
    // 根绝配件销售单号查询配件销售单详情
    async querySalesPartOrderDataBySalesPartNo(salesPartNo) {
      this.pageIsLoading = true;
      try {
        let res = await queryCancelSettlementPartRepairOrderDetail({ salesPartNo });
        if (res.resultCode == 200) {
          // 手动处理部分字段
          res.data.DISCOUNT_AMOUNT = res.data.TOTAL_DISCOUNT_AMOUNT;
          res.data.OWNER_NAME = res.data.CUSTOMER_NAME;
          res.data.ARR_BALANCE = res.data.ARR_BALANCE == 10041001 ? 1 : 0;
          res.data.REMARKDETAIL = res.data.REMARK1;

          // 查询优惠模式(翻译用)
          res.data.DISCOUNT_MODE_CODE && this.queryDiscountModelByCode(res.data.DISCOUNT_MODE_CODE);

          let cloneData = _.cloneDeep(res.data);
          jsonToHump(cloneData); // 费用信息部分表单字段为小写，转换后赋值
          let formLists = [...this.partSaleFormList, ...this.ballanceFormList];
          formLists.forEach(item => {
            item.initialValue = res.data[item.fieldName] || '';
          });
          this.costInfoFormList.forEach(item => {
            item.initialValue = cloneData[item.fieldName] || '';
          });

          this.salesPartTableDataSource = res.data.partlist;
          this.discountCouponTableDataSource = []; // 优惠券列表暂无
          this.receivableTableDataSource = res.data.receiveablelist;
          this.realIncomeTableDataSource = res.data.realList;
        }
      } catch (err) {
        console.log(err, '配件销售单详情获取失败');
      } finally {
        this.pageIsLoading = false;
      }
    },

    // 点击取消结算
    async handleCancelFeeSettlement() {
      let res = await cancelBalanceAccounts({
        balanceNo: findFormItem(this.ballanceFormList, 'BALANCE_NO').initialValue,
        vin: findFormItem(this.carOwnerFormList, 'VIN').initialValue,
        roNo: findFormItem(this.orderInfoFormList, 'RO_NO').initialValue,
        salesPartNo: findFormItem(this.partSaleFormList, 'SALES_PART_NO').initialValue
      });
      if (res.resultCode == 200) {
        notifyAction('取消结算成功', 'success');
        this.$emit('refeshTable');
        this.pageType = 'detail';
      }
    },
    // 点击取消/关闭
    handleCancel() {
      this.$emit('close');
    }
  }
};
</script>

<style lang="less" scoped>
.box {
  border: 1px solid #ccc;
  padding-top: @modulePadding;
  padding-right: @modulePadding;
  padding-left: @modulePadding;
  border-radius: @borderRadius;
  margin-bottom: 15px;
  box-shadow: @boxShadow;
}
.topBtnsWrap {
  display: flex;
  justify-content: space-between;
}
.detailWrap {
  position: relative;
  .left {
    position: absolute;
    left: 0;
    width: calc(100% - 310px);
    border: 1px solid @borderColor;
    border-radius: @borderRadius;
    box-shadow: @boxShadow;
    padding: @modulePadding;
  }
  .right {
    margin-left: calc(100% - 280px);
    border: 1px solid @borderColor;
    border-radius: @borderRadius;
    box-shadow: @boxShadow;
    padding: @modulePadding;
  }
}
.titleWrap {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
